<template>
	<view @click="closeAllSwipe" v-if="userStore.token && cartList.length" class="cart_layout">
		<scroll-view class="category_view" scroll-y>
			<uni-swipe-action ref='swipe'>
				<checkbox-group>
					<view class="card_good" v-for="(item,index) in cartList" :key="item.goodsId">
						<uni-swipe-action-item :right-options="options" @click='deleteItem(item.goodsId )'>
							<view class="layout">
								<view class="left">
									<label class="radio">
										<checkbox color='rgba(255, 0, 0, 1)' @click="checkboxChange(item.goodsId)"
											:checked="item.isChecked" />
									</label>
								</view>
								<view class="conter">
									<image :src="`${item.imageUrl}`" mode=""></image>
								</view>
								<view class="right">
									<view class="top">
										{{item.name}}
									</view>
									<view class="bottom">
										<view class="price">
											￥<text>{{item.price}}</text>
										</view>
										<view class="sum">
											<uni-number-box @change="changeBuyNum($event,item.goodsId,index,item.count)"
												:value="`${item.count}`" :min="1" :max="200"></uni-number-box>
										</view>
									</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</view>
				</checkbox-group>
			</uni-swipe-action>
			<!-- 底部安全区 -->
			<view style="height: 200rpx;" class="space"></view>
		</scroll-view>
	</view>

	<!-- 购物车为空 -->
	<view v-else class="">
		<!-- 登录后未添加商品 -->
		<not-logged-in v-if=" userStore.token && cartList == 0 "
			:obj="{text:'还没有添加商品，去添加~~~',button:'去购物',url:'/pages/index/index',toTabbar:true}"></not-logged-in>
		<!-- 未登录 -->
		<not-logged-in v-else></not-logged-in>
	</view>

	<!-- 计算总价 -->
	<view @click="closeAllSwipe" v-if="cartList.length && userStore.token" class="price_computer">
		<label class="radio">
			<checkbox color='rgba(255, 0, 0, 1)' @click="selectAllStatus" :checked="checkedAllGood" />
			<text>全选</text>
		</label>
		<view class="price_sum">
			合计：
			<text class="mini">￥<text style="font-size: 50rpx;">{{totalPrice}}</text>.00</text>
		</view>
		<button @click="toOrder" style="border-radius: 50rpx;font-size: 30rpx;width: 150rpx;" type="warn">去结算</button>
	</view>
</template>

<script setup>
	import useUserStore from '@/store/modules/user.js'
	import { reqCartList, reqDelCartGoods, reqUpdateCheked, reqChekeAllStatus, reqAddCart } from '@/api/cartReq.js'
	import { toast } from '../../utils/extendApi';
	import { computed } from 'vue';

	let userStore = useUserStore()
	let cartList = ref([]) // 购物车列表
	// let stepperValue = ref(1) // 进步器组件的值
	let options = ref(
		[{
			text: '删除',
			style: {
				backgroundColor: '#dd524d'
			}
		}]
	) // 滑动单元格配置
	let swipe = ref() //swipe组件实例

	// 计算属性：全选
	const checkedAllGood = computed(() => {
		return cartList.value.length !== 0 && cartList.value.every(item => item.isChecked == 1)
	})

	// 全选或全不选
	const selectAllStatus = async () => {
		let status = !checkedAllGood.value ? 1 : 0
		cartList.value.forEach(item => {
			// 改变本地状态
			item.isChecked = status
		})
		// 将状态传给服务器
		await reqChekeAllStatus(status)
	}

	// 获取购物车列表
	const getCartList = async () => {
		let { code, data } = await reqCartList()
		if (code == 200) {
			cartList.value = data
		}
	}

	// 防抖节流，让修改商品数量 0.5秒 后发送请求，并不会修改一次就发送一次
	const changeBuyNumAntiShake = () => {

		let time = null

		return function(newBuyNum, id, index, count) {
			// 清除上一次定时器
			clearTimeout(time)

			// 计算差值
			const disCount = newBuyNum - count

			// 购买数量没有改变，
			if (disCount == 0) return

			time = setTimeout(async () => {
				let result = await reqAddCart({ goodsId: id, count: disCount })

				// 更新本地购买数量
				if (result.code == 200) {
					cartList.value.forEach(item => {
						if (item.goodsId == id) {
							item.count = newBuyNum
							// 变为选择状态
							item.isChecked = 1
							return
						}
					})
				}

			}, 500)

		}
	}

	// 更新购买数量
	const changeBuyNum = changeBuyNumAntiShake()

	// 改变复选框状态
	const checkboxChange = async (id) => {
		let currCheck = 0
		cartList.value.forEach(item => {
			if (item.goodsId == id) {
				// 改变本地状态
				item.isChecked = item.isChecked === 1 ? 0 : 1;
				// 给服务器需要用的状态
				currCheck = item.isChecked
				return;
			}
		})

		let res = await reqUpdateCheked(id, currCheck);
	}

	// 滑动单元格的删除
	const deleteItem = async (id) => {
		let modelRes = await uni.showModal({
			title: "是否删除该商品"
		})

		if (modelRes.confirm) {
			let result = await reqDelCartGoods(id)
			if (result.code == 200) {
				toast({ title: '删除成功' })
				getCartList()
			}
		}
	}

	// 点击空白，关闭所有滑动单元格
	const closeAllSwipe = () => {
		swipe.value.closeAll()
	}

	// 购物车总金额
	const totalPrice = computed(() => {
		let sumPrice = 0
		cartList.value.forEach(item => {
			if (item.isChecked == 1) {
				sumPrice += item.price * item.count
			}
		})
		return sumPrice
	})

	// 跳转订单结算页面
	const toOrder = () => {
		// 根据结算价格判断，是否有选择的商品
		if (totalPrice.value === 0) {
			toast({ title: '请选择商品' })
		} else {
			uni.navigateTo({
				url: '/modules/orderPayModule/pages/order/detail/detail'
			})
		}
	}

	// 离开页面关闭滑块
	onHide(() => {
		swipe.value.closeAll()
	})

	onShow(() => {
		getCartList()
	})
</script>


<style lang='scss' scoped>
	.cart_layout {
		width: 100%;
		height: 100%;
		padding: 18rpx;
		background-color: rgba(207, 207, 207, 0.3);

		.category_view {
			width: 100%;
			height: 100vh;

			uni-swipe-action {
				width: 100%;
				height: 100%;

				.card_good {
					width: 100%;
					height: 100%;

					uni-swipe-action-item {
						width: 100%;
						height: 100%;

						.layout {
							width: 100%;
							height: 280rpx;
							margin: 10rpx 0;
							border-radius: 16rpx;
							background-color: white;
							display: flex;
							justify-content: center;
							align-items: center;

							.left {
								flex: 1;
								height: 100%;

								.radio {
									margin-left: 5rpx;
									width: 100%;
									height: 100%;
									display: flex;
									justify-content: center;
									align-items: center;
								}
							}

							.conter {
								flex: 6;
								height: 100%;
								display: flex;
								justify-content: center;
								align-items: center;

								image {
									width: 260rpx;
									height: 260rpx;
								}
							}

							.right {
								flex: 8;
								height: 100%;
								display: flex;
								flex-direction: column;
								justify-content: space-between;

								.top {
									white-space: normal
								}

								.bottom {
									display: flex;
									justify-content: space-between;

									.price {
										float: right;
										color: #fa4126;
										font-size: 40rpx;
										line-height: 48rpx;
									}

									.sum {
										width: 200rpx;
										display: flex;
										margin: 0 10rpx 10rpx 0;
									}
								}
							}
						}
					}
				}

			}
		}


	}

	.price_computer {
		position: fixed;
		bottom: 0;
		height: 170rpx;
		width: 100%;
		background-color: white;
		border-radius: 16rpx;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
		z-index: 99;
		display: flex;
		justify-content: flex-start;
		align-items: center;

		.radio {
			margin-left: 10rpx;
		}

		.price_sum {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			margin: 0 40rpx;

			.mini {
				color: red;
				font-size: 30rpx;
			}
		}
	}
</style>